package com.itheima.reggie.controller;

import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.apache.tomcat.util.bcel.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * 员工的控制器
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private HttpSession session;//让ioc容器为我们注入会话对象

    /**
     * 登录
     * @return
     *
     * {"username":"admin","password":"123456"}
     */
    @PostMapping("/login")
    public ResultInfo login(@RequestBody Map<String,String> map){
        //1.从map中获取请求参数
        String username = map.get("username");
        String password = map.get("password");
        //2.使用用户名和密码登录
        ResultInfo resultInfo = employeeService.login(username, password);
        //3.把查询结果存入会话共享区域  --------------------------------------*
        if(resultInfo.getData() != null){
            Employee employee = (Employee)resultInfo.getData();
            //存入会话域中
            session.setAttribute(Constant.SESSION_EMPLOYEE,employee);
        }
        //4.响应浏览器
        return  resultInfo;
    }

    /**
     * 退出登录
     * @return
     */
    @PostMapping("/logout")
    public ResultInfo logout(){
        //清理会话共享区域
        session.invalidate();
        //返回值
        return ResultInfo.success(null);
    }

    /**
     * 查询员工列表，根据姓名查询员工
     * @return
     */
    @GetMapping("/find")
    public ResultInfo findList(String name){
        //根据姓名查询员工列表
        List<Employee> employees = employeeService.findByName(name);
        //确定返回值
        return ResultInfo.success(employees);
    }

    /**
     * 保存
     * @param employee
     * @return
     */
    @PostMapping()
    public ResultInfo save(@RequestBody Employee employee){
        //调用service完成保存
        employeeService.save(employee);
        //返回
        return ResultInfo.success(null);
    }

    @GetMapping("/{id}")
    public ResultInfo findById(@PathVariable Long id){
        Employee employee = employeeService.findById(id);
        return ResultInfo.success(employee);
    }

    @PutMapping()
    public ResultInfo update(@RequestBody Employee employee){
        employeeService.update(employee);
        return ResultInfo.success(null);
    }

}
